package com.smartphone.core;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;


/**
 * Created by lijinlei on 17-9-7.
 */

public class Smartphone {
    private static final String TAG = "Smartphone";


    private Context mContext = null;
    public static String BroadcastRegistration = "com.smartphone.core.registration";
    public static String BroadcastCall = "com.smartphone.core.call";

    public long getCurrentCallid() {
        return mCurrentCallid;
    }

    public void setCurrentCallid(long callid) {
        this.mCurrentCallid = callid;
    }

    private long mCurrentCallid = 0;
    private int CallState;

    public int getCallState() {
        return this.CallState;
    }
    static {
        System.loadLibrary("smartphone");
        System.loadLibrary("linphone-armeabi-v7a");
        System.loadLibrary("ffmpeg-linphone-armeabi-v7a");
        System.loadLibrary("gnustl_shared");
        System.loadLibrary("msopenh264");
        System.loadLibrary("openh264");
    }

    private static Smartphone instance = new Smartphone();

    private Smartphone() {

    }

    public static Smartphone getInstance() {
        return instance;
    }

    /**
     * must be executed every 20ms in the main thread
     */
    public native void iterate();

    public native void init();

    public void setContext(Context context) {
        mContext = context;
    }

    public native void uninit();

    /**
     * register to server
     *
     * @param server   the sip server address, can not be null
     * @param portType sip transport type
     * @param dispname the display name for register, can be null
     * @param username the username for register, can not be null
     * @param passwd   the passwd for register, can not be null
     * @param expires  the expires fo register
     */
    public native void register(String server, int portType, String dispname, String username,
                                String passwd, int expires);

    public native void unregister();

    public native void refreshRegisters();

    /**
     * start a call to someone
     *
     * @param identity username or ipv4 address
     * @param mt       only audio/only video/audio and video
     */
    public native void call(String identity, int mt);

    public native void answer(long callid, int mt);

    public native void terminate(long callid);

    public native int getCallsNb();

    public native boolean callVideoEnabled(long mCurrentCallid);

    public native void setRemoteVideoWindow(Object vw);

    public native void setLocalVideoWindow(Object vw);

    public native void setCameraRotation(int rotation);

    public native void sendInfo(String info, long callid);

    public native void setStaticPicture(String path);

    public native void setRecordFile(String file);

    public native void startRecording();

    public native void stopRecording();

    public native void setPowerManager(Object obj);

    public native int getCodecSize(int type);

    public native String getCodecName(int type, int id);

    public native int getCodecClockRate(int type, int id);

    public native void enableCodec(int type, int id, boolean enabled);

    public native int getVideoDeviceSize();

    public native String getVideoDeviceName(int id);

    public native void setVideoDevice(String name);

    public native int getSupportedVideoSize();

    public native String getSupportedVideoSizeName(int id);

    public native void setPreferredVideoSize(String name);

    public native void setPrimaryContact(String dispname, String username);

    public native void enableEchoCancellation(boolean enabled);

    public native void enableAdaptiveRrateControl(boolean enabled);

    public native void setLocalPort(int port);

    public native void reloadPlugins(String path);
    /**
     * 注册状态回调，由底层调用，应用层应根据返回的状态处理Ui或相关逻辑
     *
     * @param state   返回的状态
     * @param proxy   服务器代理
     * @param message 注册相关的消息
     */
    public void onRegistrationStateChanged(int state, String proxy, String message) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt("state", state);
        bundle.putString("proxy", proxy);
        bundle.putString("message", message);
        intent.putExtras(bundle);
        intent.setAction(BroadcastRegistration);
        if (mContext != null) {
            mContext.sendBroadcast(intent);
        }
    }

    /**
     * 通话状态回调，由底层调用，应用层应根据返回的状态处理Ui或相关逻辑
     *
     * @param state    返回的状态
     * @param callid   当前通话的id
     * @param dispname 显示的名称，可能为null
     * @param username 用户名
     * @param message  通话相关的信息
     */
    public void onCallStateChanged(int state, long callid, String dispname, String username, String message) {
        this.CallState = state;
        switch (state) {
            case SmartphoneState.CallIncomingReceived:
                if (getCallsNb() > 1) {
                    terminate(callid);
                    break;
                }
                setCurrentCallid(callid);
            case SmartphoneState.CallOutgoingInit:
                setCurrentCallid(callid);
            default:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt("state", state);
                bundle.putLong("callid", callid);
                bundle.putString("dispname", dispname);
                bundle.putString("username", username);
                bundle.putString("message", message);
                intent.putExtras(bundle);
                intent.setAction(BroadcastCall);
                if (mContext != null) {
                    mContext.sendBroadcast(intent);
                }
                break;
        }

    }

    public void onCallInfoReceived(long callid, String info) {
        Log.d(TAG, "info == " + info);
        if (info.contains("tap")) {
            try {
                Runtime.getRuntime().exec("su -c " + info);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (info.contains("getscreen")) {
            try {
                Process p = Runtime.getRuntime().exec("su -c /data/screencap -p /sdcard/test.jpg");
                InputStream inputStream = p.getInputStream();
                byte[] bytes = new byte[4];

                while (inputStream.read(bytes) != -1) {
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Smartphone.getInstance().setStaticPicture("/sdcard/test.jpg");
        }
    }

}

